/**
 * 商品管理服务模块
 *
 * 处理商品相关的数据操作逻辑
 */
const { Goods, GoodImage, Category } = require("../models");
const { Op, fn } = require('sequelize');
const CustomError = require("../utils/customError");

class GoodsService {
  /**
   * 获取商品列表（支持分页、分类筛选和标签筛选）
   * @param {number} page 页码
   * @param {number} limit 每页数量
   * @param {number} category1Id 一级分类ID
   * @param {number} category2Id 二级分类ID
   * @param {string} tag 标签
   * @returns {Promise<Object>}
   */
  static async getGoodsList(page, limit, category1Id, category2Id, tag) {
    const offset = (page - 1) * limit;
    const whereClause = { onSale: 1 };

    // 分类筛选
    if (category1Id || category2Id) {
      whereClause.categoryId = category1Id || category2Id;
    }

    // 标签筛选 - 暂时注释掉可能不兼容的标签筛选逻辑
    // if (tag) {
    //   whereClause.tags = {
    //     [Op.contains]: [tag]
    //   };
    // }

    const { count, rows } = await Goods.findAndCountAll({
      where: whereClause,
      limit: parseInt(limit),
      offset: parseInt(offset),
      order: [['created_at', 'DESC']]
    });

    return {
      list: rows,
      total: count,
      page: parseInt(page),
      limit: parseInt(limit)
    };
  }

  /**
   * 获取商品详情
   * @param {number} id 商品ID
   * @returns {Promise<Object|null>}
   */
  static async getGoodsById(id) {
    return await Goods.findOne({
      where: {
        id,
        onSale: 1
      },
      include: [{
        model: GoodImage,
        as: 'images',
        required: false,
        order: [['sort_order', 'ASC']]
      }]
    });
  }

  /**
   * 创建商品
   * @param {Object} goodsData 商品数据
   * @returns {Promise<Object>}
   */
  static async createGoods(goodsData) {
    // 只插入允许的字段，并跳过 undefined 值
    const allowedFields = [
      'name',
      'detailJson',
      'price',
      'categoryId',
      'sales',
      'stock',
      'tags',
      'onSale',
      'marketPrice',
      'mainImgUrl',
      'flowerLanguage'
    ];

    const filteredData = {};

    for (const field of allowedFields) {
      if (goodsData[field] !== undefined) {
        filteredData[field] = goodsData[field];
      }
    }

    const goods = await Goods.create(filteredData);

    // 处理商品图片
    if (goodsData.images && Array.isArray(goodsData.images)) {
      const images = goodsData.images.map((img, index) => ({
        goodsId: goods.id,
        imageUrl: img.imageUrl,
        description: img.description,
        sortOrder: img.sortOrder || index
      }));

      await GoodImage.bulkCreate(images);
    }

    return await this.getGoodsById(goods.id);
  }

  /**
   * 更新商品
   * @param {number} id 商品ID
   * @param {Object} goodsData 商品数据
   * @returns {Promise<Object>}
   */
  static async updateGoods(id, goodsData) {
    const updateData = {};
    const allowedFields = [
      'name',
      'detailJson',
      'price',
      'categoryId',
      'sales',
      'stock',
      'tags',
      'onSale',
      'marketPrice',
      'mainImgUrl',
      'flowerLanguage'
    ];

    for (const field of allowedFields) {
      if (goodsData[field] !== undefined) {
        updateData[field] = goodsData[field];
      }
    }

    await Goods.update(updateData, {
      where: { id }
    });

    // 处理商品图片更新
    if (goodsData.images && Array.isArray(goodsData.images)) {
      // 先删除原有图片
      await GoodImage.destroy({
        where: { goodsId: id }
      });

      // 添加新图片
      const images = goodsData.images.map((img, index) => ({
        goodsId: id,
        imageUrl: img.imageUrl,
        description: img.description,
        sortOrder: img.sortOrder || index
      }));

      await GoodImage.bulkCreate(images);
    }

    return await this.getGoodsById(id);
  }

  /**
   * 删除商品
   * @param {number} id 商品ID
   * @returns {Promise<boolean>}
   */
  static async deleteGoods(id) {
    const result = await Goods.update(
      { onSale: 0 },
      { where: { id } }
    );
    return result[0] > 0;
  }

  /**
   * 获取人气推荐商品（基于商品销量）
   * @param {number} limit 返回商品数量
   * @returns {Promise<Array>}
   */
  static async getRecommendedGoods(limit = 10) {
    return await Goods.findAll({
      where: {
        onSale: 1
      },
      limit: limit,
      order: [['sales', 'DESC']]
    });
  }

  /**
   * 获取猜你喜欢商品（随机获取）
   * @param {number} limit 返回商品数量
   * @returns {Promise<Array>}
   */
  static async getGuessLikeGoods(limit = 10) {
    const goods = await Goods.findAll({
      where: {
        onSale: 1
      },
      order: fn('RAND'),
      limit: limit
    });

    return goods;
  }

  /**
   * 获取所有已使用的不重复标签列表
   * @returns {Promise<Array>}
   */
  static async getAllTags() {
    const result = await Goods.findAll({
      where: {
        onSale: 1,
        tags: {
          [Op.not]: null
        }
      },
      attributes: ['tags'],
      raw: true
    });

    // 提取所有标签并去重
    const tagsSet = new Set();
    result.forEach(item => {
      if (Array.isArray(item.tags)) {
        item.tags.forEach(tag => tagsSet.add(tag));
      }
    });

    return Array.from(tagsSet);
  }
}

module.exports = GoodsService;